﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Boomerang.Service.Threading
{
    class ServiceManager
    {
        private bool ServiceStarted;

        static Thread MainServiceThread;

        TimeSpan pollingInterval = new TimeSpan(0, 2, 0); //Default value

        public void StartService()
        {
            Trace.TraceInformation("Starting Service");
            
            try
            {
                pollingInterval = new TimeSpan(0, 0, int.Parse(System.Configuration.ConfigurationManager.AppSettings["PoolingIntervalSeconds"]));
                Trace.TraceInformation("Loaded polling interval {0} seconds", pollingInterval.Seconds);
            }
            catch (Exception ex)
            {
                pollingInterval = new TimeSpan(0, 120, 0);
                Trace.TraceWarning("Failed to load polling interval, assuming default value 120 seconds {0}", ex.Message);
            }

            ServiceStarted = true;
            ThreadStart start = new ThreadStart(Service);
            MainServiceThread = new Thread(start);
            MainServiceThread.Start();            
            Trace.TraceInformation("Service Started");
        }

        public void StopService()
        {
            Trace.TraceInformation("Stopping Service");
            ServiceStarted = false;
            Trace.TraceInformation("Waiting for completion");
            MainServiceThread.Join(pollingInterval);
            Trace.TraceInformation("Service Stopped");
        }        

        protected void Service()
        {
            Trace.TraceInformation("Starting service working thread");

            while (ServiceStarted)
            {
                Trace.TraceInformation("Starting processing round");

                DateTime start = DateTime.Now;

                ThreadManager.DoWork();

                DateTime end = DateTime.Now;

                TimeSpan diff = end - start;

                Trace.TraceInformation("Finished processing round");

                if (diff > pollingInterval)
                {
                    Trace.TraceInformation("Not sleeping. Elapsed time greater than polling interval");
                    continue;
                }
                else
                {
                    Trace.TraceInformation("Sleeping Thread for {0}", (pollingInterval - diff));
                    Thread.Sleep(pollingInterval - diff);                    
                }
            }

            Trace.TraceInformation("Exiting Service Thread");
        
        }
    }
}
